package controller.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;


public final class JDBCConnectionController 
{
  
  private static final String URL = "jdbc:mysql://localhost:3306/filmverwaltung";
  private static final String USER_NAME = "root";
  private static final String PASSWORD = "";
  
  private static Connection readOnlyConnection;
  private static Connection connection;
  
  private static long nextId = 0;
  
  // static initializer, wird executiert wenn Klasse geladen wird
  static 
  {
    try 
    {
      Class.forName("com.mysql.jdbc.Driver");
      initConnection();
      initReadOnlyConnection();
    } 
      catch (ClassNotFoundException e) 
    {
      System.err.println("Konnte JDBC Treiber nicht laden!");
      System.exit(-815);
    } 
      catch (SQLException e) 
    {
      System.err.println("Konnte keine Connection aufbauen:\n"+
                         "URL:  "+URL+"\n"+
                         "User: "+USER_NAME+"\n"+
                         "Pwd:  "+PASSWORD);
      System.exit(-4711);
    }   
  }
  
  // private constructor verhindert instantiierung
  private JDBCConnectionController() 
  {
	  
  }

  private static void initConnection() throws SQLException 
  {
    connection = DriverManager.getConnection(URL, USER_NAME, PASSWORD);
    connection.setAutoCommit(false);
  }
  
  private static void initReadOnlyConnection() throws SQLException 
  {
    readOnlyConnection = DriverManager.getConnection(URL, USER_NAME, PASSWORD);
    readOnlyConnection.setReadOnly(true);
  }
  
  public static Connection getConnection() throws SQLException 
  {
    if (connection.isClosed()) 
    {
      initConnection();
    }
    return connection;
  }

  public static Connection getReadOnlyConnection() throws SQLException 
  {
    if (readOnlyConnection.isClosed()) 
    {
      initReadOnlyConnection();
    }
    return readOnlyConnection;
  }

  public static Long getNextId() 
  {
    return nextId++;
  }
  
  public static void rollback()
	{
		try
		{
			connection.rollback();
			connection.setAutoCommit(true);
		}
		catch(SQLException e)
		{
			e.printStackTrace();
		}
		
	}
	
	public static void startTransaction()
	{
		try 
		{
			connection.setAutoCommit(false);
		}
		catch(SQLException e)
		{
			e.printStackTrace();
		}
		
	}
	
	public static void commit()
	{
		try
		{
			connection.commit();
			connection.setAutoCommit(true);
		}
		catch(SQLException e)
		{
			e.printStackTrace();
		}
		
	}
}
